package atom.core0.http.ssl;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

import org.apache.log4j.Logger;

public class TrustManagerUtil {
	private static Logger logger = Logger.getLogger("TrustManagerUtil");

	//根据证书文件 得到 TrustManagerFactory
	public static TrustManager[] getTrustManager(String trustCert) throws Exception {
		CertificateFactory cf = CertificateFactory.getInstance("X.509");
		InputStream caInput = new BufferedInputStream(new FileInputStream(trustCert));
		Certificate ca = null;
		try {
			ca = cf.generateCertificate(caInput);
			logger.debug("ca=" + ((X509Certificate) ca).getSubjectDN());
		} finally {
			caInput.close();
		}

		// Create a KeyStore containing our trusted CAs
		KeyStore keyStore = KeyStore.getInstance("jks");
		keyStore.load(null, null);
		keyStore.setCertificateEntry("ca", ca);

		// Create a TrustManager that trusts the CAs in our KeyStore
		String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
		TrustManagerFactory tmf;
		tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
		tmf.init(keyStore);
		return tmf.getTrustManagers();
		
	}
	public static TrustManager[] getTrustAnyTrustManager(){
		TrustManager[] tm = { new TrustAnyTrustManager() }; 

		return tm;
	}
	

}
